import { baseUrl } from '../config/index'
import storage from '../utils/storage'

// 获取token
const getToken = () => {
	return new Promise(async (resolve, reject) => {
		const token = storage.get('token')
		if (token) {
			resolve(token)
		} else {
			// 重新获取token
			const newToken = await uni.request({ url: baseUrl + '/teen-eye/tecent/token', method: 'POST' }).then(res => res[1].data.data.access_token)
			storage.set('token', newToken)
			resolve(newToken)
		}
	})
}

const request = async (options = {}) => {
	// options.header = {
	// 	"Content-Type": "application/x-www-form-urlencoded"
	// }
	
	return new Promise(async (resolve, reject) => {
		uni.request({
			url: baseUrl + '/teen-eye' + options.url || '',
			method: options.type || 'GET',
			data: options.data || {},
			header: options.header || {}      
		}).then(res => {
			if (res[1].data.code == 1) {
				uni.showToast({
					title: res[1].data.msg,
					icon: 'none'
				})
			}
			resolve(res[1].data)
		}).catch(err => {
			reject(err)
		})
	})
}

const get = (url, data, options = {}) => {
	options.type = 'GET'
	options.data = data
	options.url = url
	return request(options)
}

const post = (url, data, options = {}) => {
	options.type = 'POST'
	options.data = data
	options.url = url
	return request(options)
}

export default {
	request,
	get,
	post
}